/**
 * 知识阅读
 * author:caiyl5
 * date:2016年8月31日9:51:22
 */
(function(){
	var kmMaintanceReading = {
		/**
		 * bindEvent 页面事件
		 */
		bindEvent:function(){
			//评论按钮，评论整篇文章
			$(".comment-btn").unbind().on("click",function(){
				var comment_contant = $(this).siblings("#comment_content").val();
				//console.log(comment_contant);
				if (comment_contant.length<5) {
					layer.msg('您评论的内容少于5个字');
				} else {
					var param={
						"comment_contant":comment_contant,
						"pk_user":window.localStorage.userid,
						"pk_publish":kmMaintanceReading.getQueryString("pk_publish")
					};
					kmMaintanceReading.sendComment(param);
				}
			});
			//回复评论发送按钮
			$(".send-btn").unbind().on("click",function(){
				var comment_contant = $(this).siblings(".reply-people").val();
				if (comment_contant.length<5) {
					layer.msg('您回复的内容少于5个字');
				} else {
					var param={
					"comment_contant":comment_contant,
					"pk_user":window.localStorage.userid,
					"pk_publish":kmMaintanceReading.getQueryString("pk_publish"),
					"pk_parent_comment":$(this).siblings(".reply-people").attr("data-id"),
					"pk_parent_user":$(this).siblings(".reply-people").attr("data-user")
					};
					//console.log(param);
					kmMaintanceReading.answerComment(param);
				}
			});
			//回复评论按钮
			$(".btn-reply").unbind().on("click",function(){
				// $(".btn-reply").parent().siblings(".reply-people1").slideUp();
				//弹出输入框
				$(this).parent().siblings(".reply-people1").slideToggle("slow");
			});
		},
		//初始化知识阅读内容
		initReading:function(){
			var param ={
				"pk_user":	window.localStorage.userid,
				"pk_publish":kmMaintanceReading.getQueryString("pk_publish")
			}
			//转圈
			common.showLoading();
			var url = "/kmpublish/App/queryKnowledgeAttByPK";
			common.interfaceAjaxFunction(url,param,this.queryKnowledgeAttByPKSuccess,true,"",false);
		},
		//初始化知识阅读成功回调函数
		queryKnowledgeAttByPKSuccess:function(res){
			
			//console.log(res);
			//console.log("调用接口返回JSON数据串为：" + JSON.stringify(res));
			if(res.status== "0"){
				var data = res.data[0];
				$(".knowledgetilehead").text(data.publish_title);
				//显示时间
				if (!data.publish_year||!data.publish_month||!data.publish_day) {
					$("#knowledge_time").html("未知");
				} else {
					var publish_time = data.publish_year+"."+data.publish_month+"."+data.publish_day;
					$("#knowledge_time").text(publish_time);
				}
				if (data.publish_user_name!="") {
					$("#knowledge_author").text(data.publish_user_name);
				} else {
					$("#knowledge_author").text("佚名");
				}
			    $(".knowledgetilekeycon").text(data.publish_memo);
				
				

			    var keys = data.publish_key.split(",");
				var html = "";
				for (var i=0; i < keys.length-1; i++) {
					html +=keys[i]+"、";
				};
				html +=keys[i];
				$("#knowledge_key").html(html);

				//是否有视频文件
				if(data.studioUrl!=null&&data.studioUrl!=undefined&&data.studioUrl!=""){
					$(".knowledagestudio").css("display", "block");
					var studioUrlList = data.studioUrl.split(',');
					var studioHtml='';
					for(var i=0;i<studioUrlList.length;i++){
						if(studioUrlList[i]!=''&&studioUrlList[i]!=undefined&&studioUrlList[i]!=null) {
							studioHtml += '<iframe src="' + studioUrlList[i] + '" class="knowledagestudio" height=320 width=480  frameborder=0 allowfullscreen></iframe>'
						}
					}
					$(".knowledagestudio").html(studioHtml);
				}

				if (data.achementList_pic &&data.achementList_pic.length>0) {
					 $(".knowledgetilepicture").append(" ");
					for (var i=0; i < data.achementList_pic.length; i++) {
					 var pic = data.achementList_pic[i];
					 //下载制定的文件
					 kmMaintanceReading.picDownload(pic.pk_attachment,data.achementList_pic.length);
					}
				}
				
				//文件
				if (data.achementList_oth &&data.achementList_oth.length>0) {
					 $(".knowledgetilepicdescbe").html("<span>文档</span>");
					  var ohtml="";
					for (var i=0; i < data.achementList_oth.length; i++) {	
					  var att = data.achementList_oth[i];
					  // var publishtime = att.att_year+"."+att.att_month+"."+att.att_day;
					  ohtml += '<p class="achementList_oth" data-id="'+att.pk_attachment+'"><a class="blue-color waitcallback-content comment_contant" href="javascript:void(0);">'+att.fname+"("+att.filesize+")"+'</a></p>';  
                       
					};
					$(".knowledgetilepicdescbe").append(ohtml);
					//事件监听
					$(".achementList_oth").unbind().on("click",function(){
						var dataId = $(this).attr("data-id");
						//请求参数
						var url = "/file/downloadFile/" + dataId;
						//通过iframe返回到企业+前一页面
    					var $body = $('body');
    					var $iframe = $('<iframe id="title_iframe" src="" style="border:none;width:0px;height:0px;"></iframe>');
    			        $iframe.appendTo($body);
    			        document.getElementById("title_iframe").src = common.contextPath() + url + "?radom=" + Math.random();
					});
				}
				//初始化评论列表
				kmMaintanceReading.initComment();
			}else{
				common.showTip('调用接口失败，请检查网络后重试');
			}
			//隐藏转圈
			common.hideLoading();
		},
		/**
		 * 图片的异步取得
		 */
		picDownload:function(filePk,photoLength){
			 //请求参数
			 var url = "/file/picdownload/" + filePk;
			 common.interfaceAjaxFunction(url,"",kmMaintanceReading.picDownloadSuccess,true,photoLength,false);
		},
		/**
		 * 下载成功
		 */
		picDownloadSuccess:function(res,photoLength){
			 var ohtml = '<p><img src="data:image/png;base64,'+res+'" alt=""/></p>';
			 $(".knowledgetilepicture").append(ohtml);
			//图片预览
			 if($(".knowledgetilepicture img").length == photoLength){
				 layer.ready(function(){ //为了layer.ext.js加载完毕再执行
					  layer.photos({
					    photos: '#knowledget_layer-photos'
					  });
					}); 
			 }
		},
		//初始化评论列表{"pk_user":"003","pk_publish":"3","pageNum":2,"pageSize":1}
		initComment:function(){
			common.showLoading();
			//初始化输入框 onlyOne =0查所有
			$("#comment_content").val("");
			var param={
				"pk_publish":kmMaintanceReading.getQueryString("pk_publish"),
				"pk_user":window.localStorage.userid,
				"pageSize":10,
				"pageNum":common.currentPage,
				"onlyOne":"0",
				"pk_comment": window.sessionStorage.rebackComment_comment
			};

			//请求参数
			var url = "/pc/comment/queryComment";
			common.interfaceAjaxFunction(url,param,kmMaintanceReading.queryCommentListSuccess,true,"",false);
		},
		//初始化评论成功回调
		queryCommentListSuccess:function(res){
			if(res.status== "0"){
				kmMaintanceReading.updateCommentUI(res);
			}else{
				//给出信息提示
				layer.msg(res.message);
			}
		},
		/**
		 * 更新UI
		 */
		updateCommentUI:function(res){
			$(".knowledgetilecomment").html("");
			//console.log(res);
			var add_html="";
			if (res.count==0) {
				add_html='<dl class="knowledgetiledl"><p>暂无评论，赶快评论一下吧！</p></dl>'
				$("#pageDivideContainer").hide();
			} else {
				for(var i=0;i<res.data.length;i++){
					var user_name = res.data[i].user_name;
					if (user_name == undefined || user_name == "") {
						user_name = "匿名";
					}
					var comment_content = res.data[i].comment_contant;
					var comment_time = res.data[i].comment_time;
					var pk_user = res.data[i].pk_user;
					var pk_comment = res.data[i].pk_comment;

					//用户评论html
					var comment_html ='<dl class="knowledgetiledl">'+
		                 '<dd>'+
	                     '<p><span class="name">'+user_name+'</span>：'+comment_content+'</p>'+
	                     '<p><span class="time">'+comment_time+'</span><button class="btn-reply">回复</button></p>'+
	                     '<p class="reply-people1"  style="display:none">'+
	                     '<textarea name="" cols="" placeholder="我要回复评论~~" rows="" class="reply-people" data-id="'+pk_comment+'" data-user="'+pk_user+'" ></textarea>'+
	                     '<button class="comment-btn send-btn">发送</button>'+
	                     '</p>'+
		                 '</dd>'+
		             '</dl>';

					//管理员评论html
					var reply_html ="";
					for(var j=0;j<res.data[i].data.length;j++){
						var reply_user =res.data[i].data[j].user_name;
						var reply_time = res.data[i].data[j].comment_time;
						var reply_content = res.data[i].data[j].comment_contant;
					 	reply_html +='<dl class="knowledgetiledl knowledgetiledl-reply">'+
						'<dd>'+
	                    '<p><span class="name">'+reply_user+'</span> 回复'+
	                    '<span class="name">'+user_name+'</span>'+reply_content+'</p>'+
	                    '<p><span class="time">'+reply_time+'</span></p>'+
		                '</dd>'+
		             	'</dl>';
			 		}
					//一条评论html
					add_html +=comment_html+reply_html;
				}
			}

			$(".knowledgetilecomment").html(add_html);
			//隐藏转圈
			common.hideLoading();
			//绑定点击事件
			kmMaintanceReading.bindEvent();
			//产生分页结构
			common.getPageDivide(res.count,"pageDivideContainer",kmMaintanceReading.initComment,10);
		
		},
		//发送评论、、
		sendComment:function(res){
			//转圈
			common.showLoading();
			var url = "/pc/comment/addComment";
			//console.log(res);
			common.interfaceAjaxFunction(url,res,this.sendCommentSuccess,true,"",false);
		},
		//发送成功回调、、
		sendCommentSuccess:function(res){
			//console.log(res);
			if(res.status== "0"){
				common.hideLoading();
				layer.msg("评论成功");
				//console.log(res);
				//初始化输入框
				$("#comment_content").val("");
				kmMaintanceReading.initComment();
			}else{
				//给出信息提示
				layer.msg(res.message);
			}

			
		},
		//回复评论、、
		answerComment:function(res){
			//转圈
			common.showLoading();
			var url = "/pc/comment/answer";
			//console.log(res);
			common.interfaceAjaxFunction(url,res,this.answerCommentSuccess,true,"",false);
		},
		//回复评论成功回调、、
		answerCommentSuccess:function(res){
			//console.log(res);
			if(res.status== "0"){
				common.hideLoading();
				layer.msg("回复评论成功");
				kmMaintanceReading.initComment();
			}else{
				//给出信息提示
				layer.msg(res.message);
			}

		},

		//获取url中的参数值
		getQueryString:function(name) {
		    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
		    var r = window.location.search.substr(1).match(reg);
		    if (r != null) {
		        return unescape(r[2]);
		    }
		    return null;
		}
	};
	$(document).ready(function(){
		//初始化当前页
		common.currentPage=1;
		//获取知识标题id --pk_publish
		//console.log(kmMaintanceReading.getQueryString("pk_publish"));
		//绑定事件
		kmMaintanceReading.bindEvent();
		//初始化知识阅读界面
		kmMaintanceReading.initReading();
	});
})();
